package models

import (
	"time"
	"github.com/jinzhu/gorm"
	"strconv"
)

type Role struct {
	ID          int       `gorm:"primary_key" json:"id"`
	Name        string    `json:"name"`
	DisplayName string    `json:"display_name"`
	Description string    `json:"description"`
	Sort        int       `json:"sort"`
	IsEnabled   int       `json:"is_enabled"`
	IsDeleted   int       `json:"is_deleted"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

type AdminRole struct {
	AdminId int
	RoleId  int
}

func (r Role) TableName() string {
	return "roles"
}

func (ar AdminRole) TableName() string {
	return "admin_role"
}

// 获取单个角色

func GetRole(id int) (*Role, error) {
	var role Role
	err := DB.Select("*").Where("id=?", id).First(&role).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return &role, nil
}

// 统计角色列表条数

func CountRole(name string) (int, error) {
	var count int
	wheres := make(map[string]interface{})

	if name != "" {

		wheres["name"] = name
	}

	if err := DB.Model(&Role{}).Where(wheres).Count(&count).Error; err != nil {
		return 0, err
	}
	return count, nil
}

// 获取角色列表
func GetRoles(name string, begin_time string, end_time string, page int, pageSize int) ([]*Role, *Paginator) {
	var data []*Role
	item := DB.Table("roles").Find(&data)
	if name != "" {
		item = item.Where("name like ?", "%"+name+"%")
	}
	if begin_time != "" {
		item = item.Where("created_at > ?", begin_time)
	}
	if end_time != "" {
		item = item.Where("created_at < ?", end_time)
	}

	var count int
	item.Count(&count)
	paginate := NewPage(page, pageSize, count)
	err := item.Offset(paginate.Offset).Limit(paginate.Limit).Find(&data).Error
	if err != nil {
		panic(err)
	}
	return data, &paginate

}

func GetRolesNoPage(name string, begin_time string, end_time string) ([]*Role, error) {
	var data []*Role
	item := DB.Table("roles").Where("is_enabled=?",0).Find(&data)
	if name != "" {
		item = item.Where("name like ?", "%"+name+"%")
	}
	if begin_time != "" {
		item = item.Where("created_at > ?", begin_time)
	}
	if end_time != "" {
		item = item.Where("created_at < ?", end_time)
	}
	err := item.Error
	if err != nil {
		return nil, err
	}
	return data, nil
}

// 添加角色
func AddRole(data map[string]interface{}) error {
	role := Role{
		Name:        data["name"].(string),
		DisplayName: data["display_name"].(string),
		Description: data["description"].(string),
		Sort:        data["sort"].(int),
		CreatedAt:   time.Now(),
	}

	if err := DB.Create(&role).Error; err != nil {
		return err
	}
	return nil
}

// 修改角色
func (a *Role) UpdateRole() error {
	data := map[string]interface{}{
		"name":         a.Name,
		"display_name": a.DisplayName,
		"description":  a.Description,
		"sort":         a.Sort,
		"is_enabled":   int(a.IsEnabled),
		"updated_at":   a.UpdatedAt,
	}
	err := DB.Table("roles").Where("id=?", a.ID).Updates(data).Error
	if err != nil {
		return err
	}
	return nil

}

// 删除角色

func DeleteRole(id int) error {
	if err := DB.Delete(Role{}, "id=?", id).Error; err != nil {
		return err
	}
	if err := DB.Delete(PermissionRole{}, "role_id=?", id).Error; err != nil {
		return err
	}
	return nil
}

// 启用禁用角色

func IsEnableRole(id int, is_enabled int) error {
	if err := DB.Table("roles").Where("id=?", id).Update("is_enabled", is_enabled).Error; err != nil {
		return err
	}
	return nil
}

//func GetRolePermissionAll(role_id int) ([]*PermissionRole){
//	var data []*PermissionRole
//	 _ = DB.Table("permission_role").Select([]string{"permission_id"}).Where("role_id=?", role_id).Find(&data).Error
//	logging.Info(data)
//	 return  data
//}

// 获取角色对应的权限
func GetRolePermissionAll(role_id int) ([]int) {
	var data []int
	rows, _ := DB.Table("permission_role").Select("permission_id").Where("role_id=?", role_id).Rows()
	for rows.Next() {
		var permission_id int
		_ = rows.Scan(&permission_id)
		data = append(data, permission_id)
	}
	return data
}

// 修改角色权限
func UpdatePermissionRole(role_id int, permission_id []string) error {

	tx := DB.Begin()

	if err := tx.Table("permission_role").Where("role_id=?", role_id).Delete(PermissionRole{}).Error; err != nil {
		//Rollback
		tx.Rollback()
		return err
	}
	tx.Commit()
	for i := 0; i < len(permission_id); i++ {
		id, _ := strconv.Atoi(permission_id[i])
		data := PermissionRole{PermissionId: id, RoleId: role_id}
		DB.Table("permission_role").Create(data)
	}
	return nil
}

func FindRolePermission(role_id int, api_url string) bool {
	var num int
	err := DB.Table("permission_role t1").Select("t2.*").Joins("left join permissions t2 on t1.permission_id = t2.id").Where("t1.role_id=? and t2.api_url=?", role_id, api_url).Count(&num).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false
	}
	if num > 0 {
		return true
	}
	return false
}
